package org.future.persistent.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 数据库连接管理类
 * @author dycc
 *
 */

public class ConnDB {
	
	private static String resourcePath = "datasource";
	protected static String driver;	
	protected static String url;
	protected static String username;
	protected static String password;
	protected static Connection conn;
	protected Statement stmt;
	protected ResultSet rs;
	private static ConnDB connDB;
	
	// singletons
	private ConnDB(){		
		init();		
	}
	// get a instance of ConnDB
	public static ConnDB getInstance(){
	    if(connDB == null){
	        connDB = new ConnDB();
	    }
	    return connDB;
	}
	//init
	private void init(){		
		try{
			ResourceBundle resources = ResourceBundle.getBundle(resourcePath);
			
			driver = resources.getString("dataSource.driverClassName");			
			url = resources.getString("dataSource.url");						
			username = resources.getString("dataSource.username");
			password = resources.getString("dataSource.password");
			
		}catch(MissingResourceException mre){
			System.out.println("Missing Resource db_zh_CN.properties");
		}	
		// load the database driver
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//connect 
	private boolean connect(){
		try {
		    if(conn != null && !conn.isClosed()){
	            return true;
	        }
			conn = DriverManager.getConnection(url,username,password);
		}catch(SQLException se){
			se.printStackTrace();
			return false;
		}finally{			
		}
		return true;
	}
	
	//select 
	public ResultSet query(String sql){
	    // 获取连接
	    connect();
	    rs = null;
		try {
		    // ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY
			stmt = conn.createStatement();     			
			rs = stmt.executeQuery(sql);			
		} catch (SQLException e) {
			System.out.println("查询错误:"+sql);
			e.printStackTrace();
		}
		return rs;
	}
	
	//insert update delete
	public int update(String sql){
	    // 获取连接
        connect();
		int result = 0;
		try {
			stmt = conn.createStatement();
			result = stmt.executeUpdate(sql);			
		} catch (SQLException e) {
			System.out.println("更新错误:"+sql); 
			e.printStackTrace();
		}
		return result;
	}
	//closeConnection
	public void closeConnect(){
		try {
			if(conn != null && !conn.isClosed())
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
		    conn = null;
		}
	}	
	/**
	 * 数据库连接配置文件
	 * @return
	 */
	public static String getResourcePath() {
        return resourcePath;
    }
	public static void setResourcePath(String resourcePath) {
        ConnDB.resourcePath = resourcePath;
    }
}
